﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace FunctionalProgramming.PatternMatching.CollectionMatchingRules
{
   internal class ElementsAndRest<T> : ICollectionMatchingRule<T>
   {
      private readonly T[] elements;
      private readonly Action<IEnumerable<T>> action;

      public ElementsAndRest(Action<IEnumerable<T>> action, T[] elements)
      {
         this.elements = elements;
         this.action = action;
      }

      public bool DoesCollectionMatch(IEnumerable<T> collection)
      {
         bool result = true;

         T[] collectionAsArray = collection.ToArray();
         if (collectionAsArray.Length >= elements.Length)
         {
            for (int i = 0; i < elements.Length; i++)
            {
               if (!collectionAsArray[i].Equals(elements[i]))
               {
                  result = false;
                  break;
               }
            }
         }
         else
         {
            result = false;
         }

         return result;
      }

      public void ExecuteWithCollection(IEnumerable<T> collection)
      {
         IEnumerable<T> collectionWithoutElements = collection.Skip(elements.Length);
         action(collectionWithoutElements);
      }
   }
}